import sys, os

def combine1(name):
    hsuffix = ["_h_0.txt","_h_0.1.txt","_h_0.05.txt"]
    msuffix = ["_m_0.txt","_m_0.1.txt","_m_0.05.txt"]
    hout = [name+"_h_0.out", name+"_h_1.out", name+"_h_1.out"]
    mout = [name+"_m_0.out", name+"_m_1.out", name+"_m_1.out"]
    hlist=[name+s for s in hsuffix]
    mlist=[name+s for s in msuffix]
    hv = [0,1,1]
    mv = [0,1,1]
    for i in range(len(hlist)):
        filter_m(hlist[i], hout[i], hv[i]) #filter_h
    for i in range(len(mlist)):
        filter_m(mlist[i], mout[i], mv[i])
    for h in [name+"_h_0",name+"_h_1",name+"_m_0",name+"_m_1"]:
        os.system("subset.py "+h+".out 250 "+h+".train "+h+".predict")
    os.system("del "+name+"_?_?.out")
    os.system("copy "+name+"_h_0.predict+"+name+"_h_1.predict "+name+"_h.predict")
    os.system("copy "+name+"_m_0.predict+"+name+"_m_1.predict "+name+"_m.predict")
    os.system("copy "+name+"_h_0.train+"+name+"_h_1.train "+name+"_h.train")
    os.system("copy "+name+"_m_0.train+"+name+"_m_1.train "+name+"_m.train")
    os.system("del "+name+"_?_?.train")
    os.system("del "+name+"_?_?.predict")

def filter_m(nm, nmout, v):
    fin=open(nm,"rt")
    fout=open(nmout,"a")
    for line in fin:
        line=line.strip()
        if not line:
            continue
        p = line.split()
        if len(p) < 2:
            continue
        # print line.split(' ',1)
        [lbl, fea] = line.split(' ',1)
        fout.write("%d %s\n" %(v,fea))
    fin.close()
    fout.close()

def filter_h(nm, nmout, v):
    fin=open(nm,"r")
    fout=open(nmout,"w")
    for line in fin:
        line=line.strip()
        if not line:
            continue
        # print line
        nodes = line.split()[1:]
        if not nodes:
            continue
        d0 = []
        n = []
        s = 0.0
        for node in nodes:
            p, q = node.split(":",1)
            q = float(q)
            p = int(p)
            d0.append(q)
            n.append(p)
            s = s+q
        fout.write("%d" %v)
        d = [q/s for q in d0]
        for i in range(len(d)):
            fout.write(" %d:%.5f"%(n[i],d[i]))
        fout.write("\n")
    fin.close()
    fout.close()


if __name__=='__main__':
    if len(sys.argv) < 2:
        print 'usage: ',sys.argv[0],'<input_name>'
        exit(2)

    combine1(sys.argv[1])

